/*
 * @Author: zhangzhen
 * @Date: 2022-07-21 14:05:11
 * @LastEditors: zhangzhen
 * @LastEditTime: 2023-04-18 13:42:12
 *
 */

import { useState } from 'react'
import { useAppDispatch, useAppSelector } from '@/redux/hook'
import { setConfigs, setIconArr } from '@/redux/slice'
import styles from './index.module.scss'
import { shallowEqual } from 'react-redux'
import { Button, Modal, Form, Input, Popconfirm } from 'antd'

const IconEdit = () => {
  const { iconArr } = useAppSelector(({ state }) => ({ ...state }), shallowEqual)
  const dispatch = useAppDispatch()
  const [open, setOpen] = useState<boolean>(false)
  const [form] = Form.useForm()

  const onFinish = () => {
    form.validateFields().then((values) => {
      dispatch(setIconArr([...iconArr, values]))
      setOpen(false)
    })
  }

  return (
    <div className={styles.editIconPage}>
      <div>
        <Button
          type="primary"
          onClick={() => {
            setOpen(true)
          }}
        >
          添加
        </Button>
      </div>
      <div className={styles.editIconBox}>
        {iconArr.map((item, index) => {
          return item.iconUrl ? (
            <Popconfirm
              title="确认删除图标吗？"
              okText="确认"
              cancelText="取消"
              onConfirm={() => {
                const arr = [...iconArr]
                arr.splice(index, 1)
                dispatch(setIconArr(arr))
              }}
            >
              <img src={item.iconUrl} key={item.url} title={item.name} alt={item.name} className={styles.editIcon} />
            </Popconfirm>
          ) : (
            <Popconfirm
              title="确认删除图标吗？"
              okText="确认"
              cancelText="取消"
              onConfirm={() => {
                const arr = [...iconArr]
                arr.splice(index, 1)
                dispatch(setIconArr(arr))
              }}
            >
              <span title={item.name} className={styles.editIcon}>
                {item.name.substring(0, 1)}
              </span>
            </Popconfirm>
          )
        })}
      </div>
      <Modal
        title="添加图标"
        okText="确定"
        cancelText="取消"
        open={open}
        onCancel={() => {
          setOpen(false)
        }}
        onOk={() => {
          form.submit()
        }}
      >
        <Form form={form} onFinish={onFinish} labelCol={{ span: 5 }}>
          <Form.Item label="名称" name="name" required>
            <Input />
          </Form.Item>
          <Form.Item label="url" name="url" required>
            <Input />
          </Form.Item>
          <Form.Item label="图标url" name="iconUrl">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default IconEdit
